package com.gsbelarus.gedemin.salary.fragment.gdmsg;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.gsbelarus.gedemin.salary.App;
import com.gsbelarus.gedemin.salary.R;
import com.gsbelarus.gedemin.salary.database.RealmHelper;
import com.gsbelarus.gedemin.salary.entity.model.GdMsgModel;
import com.gsbelarus.gedemin.salary.entity.model.GdMsgVacationModel;
import com.gsbelarus.gedemin.salary.service.SendMsgDataService;
import com.gsbelarus.gedemin.salary.util.ExtractStringHelper;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import io.realm.Realm;

public class GdMsgNewVacationFragment extends Fragment implements DatePickerDialog.OnDateSetListener {

    public static final String DATEPICKER_START_TAG = "datepickerStart";
    public static final String DATEPICKER_FINISH_TAG = "datepickerFinish";

    private TextView tvStartDate;
    private TextView tvFinishDate;

    private GdMsgModel gdMsgVacation;
    private GdMsgVacationModel gdMsgVacationSubModel;

    private RealmHelper realmHelper;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);

        realmHelper = new RealmHelper(Realm.getInstance(getActivity()));

        gdMsgVacation = new GdMsgModel();
        gdMsgVacationSubModel = new GdMsgVacationModel();
        Calendar now = Calendar.getInstance();
        now.set(Calendar.HOUR_OF_DAY, 0);
        now.set(Calendar.MINUTE, 0);
        now.set(Calendar.SECOND, 0);
        gdMsgVacationSubModel.setDateBegin(now.getTime());
        gdMsgVacationSubModel.setDateEnd(now.getTime());
        gdMsgVacationSubModel.setType(GdMsgVacationModel.Type.REGULAR);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        realmHelper.getRealm().close();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.gdmsg_new_vacation_fragment, container, false);

        final Calendar calendar = Calendar.getInstance();
        final DatePickerDialog datePickerDialog = DatePickerDialog.newInstance(this,
                calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));


        tvStartDate = (TextView) view.findViewById(R.id.tvStartDate);
        tvFinishDate = (TextView) view.findViewById(R.id.tvFinishDate);

        SimpleDateFormat dateFormat = new SimpleDateFormat("d MMMM", Locale.getDefault());
        tvStartDate.setText(dateFormat.format(gdMsgVacationSubModel.getDateBegin()));
        tvFinishDate.setText(dateFormat.format(gdMsgVacationSubModel.getDateEnd()));

        EditText etComment = (EditText) view.findViewById(R.id.etComment);

        RadioGroup rgVacationType = (RadioGroup) view.findViewById(R.id.rgVacationType);
        rgVacationType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rbRegularVacation) {
                    gdMsgVacationSubModel.setType(GdMsgVacationModel.Type.REGULAR);
                } else if (checkedId == R.id.rbUnpaidVacation) {
                    gdMsgVacationSubModel.setType(GdMsgVacationModel.Type.UNPAID);
                }
            }
        });

        tvStartDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                datePickerDialog.setYearRange(calendar.get(Calendar.YEAR), calendar.get(Calendar.YEAR) + 1);
                datePickerDialog.show(getActivity().getFragmentManager(), DATEPICKER_START_TAG);
            }
        });
        tvFinishDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                datePickerDialog.setYearRange(calendar.get(Calendar.YEAR), calendar.get(Calendar.YEAR) + 1);
                datePickerDialog.show(getActivity().getFragmentManager(), DATEPICKER_FINISH_TAG);
            }
        });

        etComment.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                gdMsgVacation.setComment(s.toString());
            }
        });

        if (savedInstanceState != null) {
            DatePickerDialog dpd1 = (DatePickerDialog) getActivity().getFragmentManager().
                    findFragmentByTag(DATEPICKER_START_TAG);
            if (dpd1 != null) {
                dpd1.setOnDateSetListener(this);
            }
            DatePickerDialog dpd2 = (DatePickerDialog) getActivity().getFragmentManager().
                    findFragmentByTag(DATEPICKER_FINISH_TAG);
            if (dpd2 != null) {
                dpd2.setOnDateSetListener(this);
            }
        }
        return view;
    }

    @Override
    public void onDateSet(DatePickerDialog datePickerDialog, int year, int month, int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, day);

        SimpleDateFormat dateFormat = new SimpleDateFormat("d MMMM", Locale.getDefault());
        switch (datePickerDialog.getTag()) {
            case DATEPICKER_START_TAG:
                calendar.setTime(gdMsgVacationSubModel.getDateBegin());
                calendar.set(year, month, day);
                gdMsgVacationSubModel.getDateBegin().setTime(calendar.getTimeInMillis());

                tvStartDate.setText(dateFormat.format(gdMsgVacationSubModel.getDateBegin()));
                break;
            case DATEPICKER_FINISH_TAG:
                calendar.setTime(gdMsgVacationSubModel.getDateEnd());
                calendar.set(year, month, day);
                gdMsgVacationSubModel.getDateEnd().setTime(calendar.getTimeInMillis());

                tvFinishDate.setText(dateFormat.format(gdMsgVacationSubModel.getDateEnd()));
                break;
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_send:

                gdMsgVacation.setUid(realmHelper.generateUID(GdMsgModel.class));
                gdMsgVacation.setSender(GdMsgModel.Sender.CLIENT);
                gdMsgVacation.setSubject(GdMsgModel.Subject.VACATION);
                gdMsgVacation.setRequestStatus(GdMsgModel.RequestStatus.UNKNOWN);
                gdMsgVacation.setTimestamp(new Date());
                gdMsgVacationSubModel.setUid(realmHelper.generateUID(GdMsgVacationModel.class));
                gdMsgVacation.setGdMsgVacationModel(gdMsgVacationSubModel);
                gdMsgVacation.setGdMsgString(ExtractStringHelper.gdMsgToString(gdMsgVacation));

                Intent intent = new Intent(getActivity(), SendMsgDataService.class);
                intent.setAction(SendMsgDataService.SEND_GD_MSG_ACTION);
                intent.putExtra(SendMsgDataService.EXTRA_KEY_GD_MSG, gdMsgVacation);
                getActivity().startService(intent);

                getActivity().finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onResume() {
        super.onResume();
        Tracker tracker = ((App) getActivity().getApplication()).getTracker(App.TrackerName.APP_TRACKER);
        tracker.setScreenName(getClass().getSimpleName());
        tracker.send(new HitBuilders.AppViewBuilder().build());
    }
}